package com.kobe.algorithm.leetcode.case8;

/**
 * @author ：caopengfei
 * @date ：2021/2/23
 */
public class Solution {
    public int myAtoi(String s) {
        //去掉无用的空格
        boolean isPositive = true;
        while(s.startsWith(" ")){
            s = s.substring(1);
        }

        if(s.startsWith("-") || s.startsWith("+")){
            isPositive = !s.startsWith("-");
            s = s.substring(1);
        }
        int result = 0;

        for(int j = 0; j < s.length(); j++){
            int c = s.charAt(j)-'0';
            if(c>=0 && c<=9){
                if(result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE/10 && c>7)){
                    return  isPositive?Integer.MAX_VALUE:Integer.MIN_VALUE;
                }
                result = result *10 +c;
            }else{
                break;
            }
        }
        return isPositive?result:-result;
    }

    public static void main(String[] args) {
        String c = "2147483648";
        Solution solution = new Solution();
        System.out.println(solution.myAtoi(c));

    }
}
